import React, { useState, useEffect } from 'react';
import styles from './Ewm.module.css';
import QRCode from 'qrcode';
import { Button, Spin, message } from 'antd';
import { UserOutlined, QrcodeOutlined } from '@ant-design/icons';
import { saveAs } from 'file-saver';
import { useNavigate } from 'react-router-dom';
export default function Ewm() {
    const navigate = useNavigate();
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  
  const userId = localStorage.getItem('user');
  const qrData = JSON.parse(JSON.stringify({ userId }));
  useEffect(() => {
    setLoading(true);
    QRCode.toDataURL(qrData.userId, {
          errorCorrectionLevel: 'H',
          margin: 4,
           width: 256,
          color: {
        dark: '#000000', // 纯黑
    light: '#ffffffff' // 透明背景（或纯白）
      },
    }, (err, url) => {
      if (err) {
        message.error('生成二维码失败');
        console.error(err);
      } else {
        setQrCodeUrl(url);
      }
      setLoading(false);
    });
  }, [qrData]);

  const handleCopy = () => {
    saveAs(qrCodeUrl, 'img.png');
  };

  return (
    <div className={styles.container}>
      <div className={styles.card}>
        <div className={styles.header}>
          <div className={styles.avatar}>
            <UserOutlined className={styles.avatarIcon} />
          </div>
          <h3 className={styles.title}>我的二维码</h3>
        </div>
        
        <div className={styles.qrContainer}>
          {loading ? (
            <Spin size="large" tip="生成中..." />
          ) : (
            <>
              <img src={qrCodeUrl} alt="用户二维码" className={styles.qrCode} />
              <div className={styles.qrFrame}></div>
            </>
          )}
        </div>
        
        <div className={styles.userInfo}>
          <Button 
            icon={<QrcodeOutlined />}
            onClick={handleCopy}
            className={styles.copyBtn}
          >
            下载二维码
          </Button>
        </div>
        
        <div className={styles.footer}>
          <Button 
            type="primary" 
            shape="round" 
            icon={<QrcodeOutlined />}
            className={styles.scanBtn}
            onClick={()=>{
                navigate('/sao')
            }}
          >
            扫码添加好友
          </Button>
        </div>
      </div>
    </div>
  );
}